<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1000px"
    :title="titleContent"
    @close="close"
  >
    <el-form
      ref="formRef"
      class="myForm"
      :model="formData"
      :inline="true"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-form-item
        label="产品名称"
        style="width: 100%;"
      >
        <div class="product-name">{{ productDetail.productPopularName }}-{{ productDetail.approvalNumber }}-{{ productDetail.packSpecs }}</div>
      </el-form-item>
      <el-form-item
        label="价格编号"
        style="width: 47%; margin-right: 0px;"
      >
        <el-input
          v-model="formData.priceNumber"
          disabled
        />
      </el-form-item>
      <el-form-item
        class="form-item"
        label="准入模式"
        prop="accessMode"
        style="width: 47%; margin-right: 0px;"
      >
        <el-select
          v-model="formData.accessMode"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择准入模式"
        >
          <el-option
            v-for="(itm, idx) in accessModeOptions"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="适用地区"
        prop="region"
        style="width: 47%; margin-right: 0px;"
      >
        <el-cascader
          ref="cascader"
          v-model="formData.area"
          :popper-append-to-body="false"
          style="width: 100%;"
          :options="citys"
          placeholder="请选择适用地区"
          :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
          collapse-tags
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item
        class="form-item"
        label="适用终端"
        prop="terminalType"
        style="width: 47%; margin-right: 0px;"
      >
        <el-select
          v-model="formData.terminalType"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择适用终端"
        >
          <el-option
            v-for="(itm, idx) in terminalTypeOptions"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="原终端价"
        prop="terminalPrice"
        style="width: 47%; margin-right: 0px;"
      >
        <div class="scj-form-item">
          <el-input
            v-model="formData.terminalPrice"
            style="width: 100%"
            clearable
            disabled
            placeholder="请输入终端价"
          >
            <template #append>
              <div><span>元</span><span v-if="formData.sellUnit"> / {{ getLabel('sell_unit',formData.sellUnit) }}</span></div>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="指导交易价"
        style="width: 47%; margin-right: 0px;"
        prop="guidingPrice"
      >
        <div class="scj-form-item">
          <el-input
            v-model="formData.guidingPrice"
            style="width: 100%"
            clearable
            placeholder="请输入指导交易价"
            @input="formData.guidingPrice = formData.guidingPrice.replace(/^\.+|[^\d.]/g,'')"
          >
            <template #append>
              <div><span>元</span><span v-if="formData.sellUnit"> / {{ formData.sellUnit }}</span></div>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="变更终端价"
        style="width: 100%;"
        prop="changeTerminalPrice"
      >
        <el-switch
          v-model="formData.changeTerminalPrice"
          :active-value="1"
          :inactive-value="0"
          @change="isChangeTerminalPrice"
        />
      </el-form-item>
      <template v-if="formData.changeTerminalPrice===1">
        <el-form-item
          class="form-item"
          label="新终端价"
          prop="newTerminalPrice"
          style="width: 47%;margin-right: 0px;"
        >
          <div class="scj-form-item">
            <el-input
              v-model="formData.newTerminalPrice"
              style="width: 100%"
              clearable
              placeholder="请输入新终端价"
              oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
            >
              <template #append>
                <div><span>元</span><span v-if="formData.sellUnit"> / {{ formData.sellUnit }}</span></div>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="变更原因"
          prop="reason"
          style="width: 47%;margin-right: 0px;"
        >
          <div class="scj-form-item">
            <el-input
              v-model="formData.reason"
              type="textarea"
              style="width: 100%"
              clearable
              :autosize="{ minRows: 1, maxRows: 3 }"
              placeholder="请输入变更原因"
            />
          </div>
        </el-form-item>
        <el-row style="width: 100%;">
          <el-form-item
            class="form-item"
            prop="isUpdateStandard"
            style="width: 47%;margin-right: 0px;"
            :show-message="false"
          >
            <el-checkbox
              v-model="formData.isUpdateStandard"
              :true-label="1"
              :false-label="0"
              @change="updateStandardChange"
            >同时更新正常交易进货渠道关系的终端价</el-checkbox>
            <div
              v-if="isSelectTip"
              style="color: #f56c6c;height:32px;line-height:32px;"
            >{{ isSelectTip }}</div>
          </el-form-item>
        </el-row>
        <el-row
          v-if="formData.isUpdateStandard"
          style="width: 100%;"
        >
          <el-form-item
            class="form-item"
            :show-message="false"
            :prop="formData.isUpdateStandard?'standardIds':'nomarl'"
            style="width: 100%;margin-right: 0px;"
          >
            <el-table
              ref="selectTable"
              header-cell-class-name="table-header"
              :data="tableData"
              :border="true"
              max-height="260px"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                header-align="center"
                align="center"
                fixed="left"
              />
              <el-table-column
                property="terminalName"
                label="终端名称"
                header-align="center"
                :min-width="140"
                show-overflow-tooltip
                fixed="left"
              />
              <el-table-column
                label="所在地区"
                header-align="center"
                :min-width="140"
                show-overflow-tooltip
              >
                <template #default="scope">{{ scope.row.provinceName }} / {{ scope.row.cityName }} / {{ scope.row.areaName }}</template>
              </el-table-column>

              <el-table-column
                property="terminalPrice"
                label="当前终端价（元）"
                header-align="center"
                align="center"
                :min-width="140"
                show-overflow-tooltip
              />
              <el-table-column
                label="更新后终端价（元）"
                header-align="center"
                align="center"
                :min-width="150"
                show-overflow-tooltip
              >
                <template #default>{{ formData.newTerminalPrice }}</template>
              </el-table-column>
              <el-table-column
                property="sellMode"
                label="营销模式"
                header-align="center"
                :min-width="120"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <span v-if="scope.row?.sellMode !== 'direct'">
                    {{ scope.row?.agentAttribute === '1' ?'独家招商':'精细招商' }}
                  </span>
                  <span v-else> 终端直销</span>
                </template>
              </el-table-column>
              <el-table-column
                label="渠道客户明细"
                header-align="center"
                :min-width="140"
                show-overflow-tooltip
              >
                <template #default="scope">
                  <div v-if="scope.row.agentDetail?.agentType==='agent'">
                    {{ scope.row.agentDetail?.agentName }}
                  </div>
                  <div v-if="scope.row.agentDetail?.agentType==='agent_person'">
                    {{ scope.row.agentDetail?.userName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                property="tradePrice"
                label="交易价（元）"
                header-align="center"
                align="center"
                :min-width="140"
                show-overflow-tooltip
              />
              <el-table-column
                property="address"
                label="配送费"
                header-align="center"
                align="center"
                :min-width="120"
                show-overflow-tooltip
                fixed="right"
              >
                <template #default="scope">
                  <div v-if="scope.row.distributeContractDetails&&scope.row.distributeContractDetails.length">
                    <distributors-view
                      placement="top"
                      :datas="scope.row.distributeContractDetails"
                      :unit="scope.row.productInfoDetail?.sellUnit"
                    />
                  </div>
                  <div v-else>无配送商</div>
                </template>
              </el-table-column>
              <el-table-column
                property="headName"
                label="负责职员"
                header-align="center"
                :min-width="100"
                show-overflow-tooltip
                fixed="right"
              >
                <template #default="scope">
                  <div>
                    {{ scope.row.headName||'无' }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
      </template>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'
import area from '@/utils/area.js'
import {crmStore} from '@CRM/store'

export default defineComponent({
  name: 'ChangePrice',
  emits: ['changeSuccess'],
  setup(props, context) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const citys = area
    const formRef = ref(null)
    var cascader = ref(null)
    var titleContent = ref('变更产品价格')
    var detailData = reactive({
      isSelectTip: '',
      terminalTypeOptions: [],
      accessModeOptions: [],
      productDetail: {},
      formData: {
        priceNumber: '',
        accessMode: '',
        area: [],
        region: [],
        terminalType: '',
        terminalPrice: '',
        changeTerminalPrice: 0,
        newTerminalPrice: null,
        reason: '',
        isUpdateStandard: 0,
        standardIdItem: [],
        standardIds: [],
      },
      tableData: [],
    })
    const newTerminalPricePass = (rule, value, callback) => {
      if (value) {
        if (Number(value) > 0) {
          if (detailData.formData.terminalPrice === Number(value)) {
            callback(new Error('新终端不能和原来的终端价相同'))
          } else {
            if (Number(value) < detailData.formData.guidingPrice) {
              callback(new Error('新终端不能小于指导交易价'))
            } else {
              detailData.formData.newTerminalPrice = Number(value)
              callback()
              formRef.value.validateField('guidingPrice')
            }
          }
        } else {
          callback(new Error('终端价必须大于0'))
        }
      } else {
        callback(new Error('请输入新终端价'))
      }
    }
    const guidingPricePass = (rule, value, callback) => {
      if (value) {
        if (detailData.formData.changeTerminalPrice === 1) {
          if (Number(value) <= detailData.formData.newTerminalPrice) {
            detailData.formData.guidingPrice = Number(value)
            callback()
          } else {
            if (detailData.formData.newTerminalPrice) {
              callback(new Error('指导交易价不能大于新终端价'))
            } else {
              callback()
            }
          }
        } else {
          if (Number(value) <= detailData.formData.terminalPrice) {
            detailData.formData.guidingPrice = Number(value)
            callback()
          } else {
            callback(new Error('指导交易价不能大于终端价'))
          }
        }
      } else {
        callback('请输入底价')
      }
    }
    const standardPass = (rule, value, callback) => {
      if (detailData.formData.isUpdateStandard) {
        if (
          detailData.formData.standardIds &&
          detailData.formData.standardIds.length
        ) {
          detailData.isSelectTip = ''
          callback()
        } else {
          detailData.isSelectTip = '请选择需要变更进货渠道关系的数据'
          callback(new Error('请选择需要变更进货渠道关系的数据'))
        }
      } else {
        detailData.isSelectTip = ''
        callback()
      }
    }
    const updatestandardPass = (rule, value, callback) => {
      if (detailData.formData.isUpdateStandard === 0) {
        callback()
      } else {
        if (
          detailData.formData.standardIds &&
          detailData.formData.standardIds.length
        ) {
          detailData.isSelectTip = ''
          callback()
        } else {
          detailData.isSelectTip = '请选择需要变更进货渠道关系的数据'
          callback(new Error('请选择需要变更进货渠道关系的数据'))
        }
      }
    }
    const changeTerminalPricePass = (rule, value, callback) => {
      if (value === 0) {
        formRef.value.validateField('guidingPrice')
        callback()
      } else {
        formRef.value.validateField('guidingPrice')
        callback()
      }
    }
    var formRules = reactive({
      accessMode: [
        { required: true, message: '请选择准入模式', trigger: 'change' },
      ],
      region: [
        { required: true, message: '请选择适用地区', trigger: 'change' },
      ],
      terminalType: [
        { required: true, message: '请选择适用终端', trigger: 'change' },
      ],
      scj: [{ required: true, message: '请输入市场价', trigger: 'blur' }],
      terminalPrice: [
        { required: true, message: '请输入终端价', trigger: 'blur' },
      ],
      newTerminalPrice: [
        { required: true, validator: newTerminalPricePass, trigger: 'blur' },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      guidingPrice: [
        {
          required: false,
          validator: guidingPricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      reason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }],
      isUpdateStandard: [
        {
          required: true,
          validator: updatestandardPass,
          trigger: 'change',
        },
      ],
      changeTerminalPrice: [
        {
          required: true,
          validator: changeTerminalPricePass,
          trigger: 'change',
        },
      ],
      standardIds: [
        {
          required: true,
          type: 'array',
          validator: standardPass,
          trigger: 'change',
        },
      ],
      nomarl: [],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const handleSelectionChange = (val) => {
      detailData.formData.standardIdItem = val
      detailData.formData.standardIds = val.map((p) => p.id) || []
    }
    const open = (detail) => {
      detailData.productDetail = detail.productDetail
      detailData.formData = detail.priceDetail
      detailData.formData.standardIds = []
      detailData.formData.standardIdItem = []
      detailData.formData.isUpdateStandard = 0
      detailData.formData.changeTerminalPrice = 0
      detailData.formData.area = currentInstance.proxy.getCascaderAreaData(
        detail.priceDetail.region
      )
      detailData.terminalTypeOptions =
        crmStore.getters['dictionary/getDictionary']['app_mode']
      detailData.priceTypeOptions =
        crmStore.getters['dictionary/getDictionary']['price_type']
      detailData.accessModeOptions =
        crmStore.getters['dictionary/getDictionary']['access_mode']
      console.log(detailData.formData)
      tradingProductPriceList(detail.priceDetail)
      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const areaChange = (val) => {
      console.log(val)
      detailData.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
    }
    // 获取使用此产品价格正在交易的列表
    const tradingProductPriceList = (priceDetail) => {
      api.product
        .TRADING_PRODUCT_PRICE_LIST({ id: priceDetail.id })
        .then((res) => {
          if (res.code === 0) {
            detailData.tableData = res.data.relationDetail
            console.log(detailData.tableData)
          }
        })
    }
    const changeClientPrice = () => {
      api.product.CHANGE_PRODUCT_PRICE(detailData.formData).then((res) => {
        if (res.code === 0) {
          context.emit('changeSuccess')
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const updateStandardChange = (val) => {
      if (val === 0) {
        detailData.formData.standardIdItem = []
        detailData.formData.standardIds = []
        detailData.isSelectTip = ''
      }
    }
    const isChangeTerminalPrice = (val) => {
      if (val === 0) {
        detailData.formData.newTerminalPrice = null
        detailData.formData.reason = ''
      }
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          changeClientPrice()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      citys,
      formRef,
      cascader,
      titleContent,
      ...toRefs(detailData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      areaChange,
      handleSelectionChange,
      updateStandardChange,
      isChangeTerminalPrice,
    }
  },
})
</script>

  <style lang="scss" scoped>
.myForm {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  .form-item {
    width: 47%;
  }
}
</style>

